// 测试环境
const baseURL = "http://101.34.108.131:4592";
// 正式环境

const request = {
  /**get请求 */
  get<T>(url: string, data?: any, header?: any) {
    return new Promise<{ data: T }>((resolve, reject) => {
      const token = localStorage.getItem("token"); //如果有token就加上token
      let lang = localStorage.getItem("lang") || "zh-CN";
      // 截取只要碰到'zh'就对应后端的中文简体(后端定义什么就是什么)
      if (lang.startsWith("zh")) lang = "zhCN";
      uni
        .request({
          url: baseURL + url,
          data: data,
          method: "GET",
          header: {
            Authorization: {
              Authorization: "Bearer " + token,
              "Accept-Language": lang,
              ...header,
            },
          },
        })
        .then((res) => {
          if (!res.data) {
            resolve(undefined as any);
          } else {
            resolve(res.data as { data: T });
          }
        })
        .catch((error) => {
          uni.showToast({
            title: "get后端请求错误",
            icon: "error",
          });
          reject(JSON.stringify(error));
        });
    });
  },
  /**post请求 */
  post<T>(url: string, data: any, header?: any) {
    return new Promise<{ data: T }>((resolve, reject) => {
      const token = localStorage.getItem("token"); //如果有token就加上token
      let lang = localStorage.getItem("lang") || "zh-CN";
      // 截取只要碰到'zh'就对应后端的中文简体(后端定义什么就是什么)
      if (lang.startsWith("zh")) lang = "zhCN";
      uni
        .request({
          url: baseURL + url,
          data: data,
          method: "POST",
          header: {
            Authorization: {
              Authorization: "Bearer " + token,
              "Accept-Language": lang,
              ...header,
            },
          },
        })
        .then((res) => {
          if (!res.data) {
            resolve(undefined as any);
          } else {
            resolve(res.data as { data: T });
          }
        })
        .catch((error) => {
          uni.showToast({
            title: "get后端请求错误",
            icon: "error",
          });
          reject(JSON.stringify(error));
        });
    });
  },
};
export { request };